package org.mspring.mlog.api.rss;

import java.util.List;

import org.mspring.mlog.core.ServiceFactory;
import org.mspring.mlog.entity.News;
import org.mspring.mlog.service.NewsService;
import org.mspring.mlog.service.OptionService;
import org.mspring.platform.api.rss.elements.Channel;
import org.mspring.platform.api.rss.elements.Item;
import org.mspring.platform.api.rss.writers.RSSWriter;
import org.mspring.platform.api.rss.writers.RSSWriterFactory;
import org.mspring.platform.utils.StringUtils;

/**
 * 
 * @author Gao Youbo
 * @since 2013年7月26日
 */
public class NewsRSSGen {
    public String gen() {
        OptionService optionService = ServiceFactory.getOptionService();
        String sitename = optionService.getOption("sitename");
        String siteurl = optionService.getOption("siteurl");
        String subname = optionService.getOption("subname");

        NewsService newsService = ServiceFactory.getBean(NewsService.class);
        List<News> newsList = newsService.recent(100);

        Channel channel = new Channel();
        channel.setLink(siteurl);
        channel.setTitle(sitename + "最新新闻资讯");
        channel.setDescription(sitename + "--" + subname);
        channel.setImage(siteurl, sitename, siteurl + "/images/logo.png");
        channel.setGenerator(sitename + "(" + siteurl + ")");

        for (News news : newsList) {
            String url = siteurl + "/news/" + news.getId();
            String description = StringUtils.isNotBlank(news.getSummary()) ? news.getSummary() : StringUtils.contentTransform(news.getContent(), false, false, 0, 1000);
            Item item = new Item();
            item.setLink(url);
            item.setTitle(news.getTitle());
            item.setDescription(description);
            item.setDcDate(news.getCreateTime());
            item.setDcContributor(news.getAuthor().getAlias());
            item.addCategory(news.getCatalog().getName());
            channel.addItem(item);
        }
        try {
            RSSWriter writer = RSSWriterFactory.getWriter("2.0");
            return writer.getFeed(channel);
        } catch (Exception e) {
            // TODO: handle exception
            return null;
        }

    }
}
